package com.example.demo.api;


import com.example.demo.entity.Device;
import com.example.demo.helper.RUtil;
import com.example.demo.service.DeviceService;
import com.example.demo.vo.BTPageDO;
import com.example.demo.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;



@RestController
@Slf4j
public class DeviceRestController {

    @Autowired
    private DeviceService deviceService;

    /**
     * 基本分页
     * @param offset
     * @param limit
     * @return
     */
    @RequestMapping(value = "/api/device/list")
    public BTPageDO<Device> list(int offset, int limit){

        int pageIndex=offset/limit;
        int pageSize=limit;

        Page<Device> myList=deviceService.findByPage(pageIndex,pageSize);

        BTPageDO<Device> stuList=new BTPageDO<Device>();
        stuList.setLimit(pageSize);
        stuList.setOffset(pageIndex);
        stuList.setRows(myList.getContent());
        Long total=myList.getTotalElements();
        stuList.setTotal(total.intValue());

        return  stuList;


    }


    @GetMapping("/api/device/read")
    public R read(Integer id){
        Device device= deviceService.findById(id).get();

        return RUtil.success(device);

    }


//    @PostMapping(value = "/api/device/add")
//    public R add(@Valid Device device, BindingResult bindingResult){
//
//        if(bindingResult.hasErrors()){
//            log.info(bindingResult.getFieldError().getDefaultMessage());
//            return RUtil.error(-2,
//                    "出错了!"+bindingResult.getFieldError().getDefaultMessage());
//        }
//        deviceService.add(device);
//
//        return RUtil.success();
//
//    }







    @DeleteMapping(value = "/api/device/delete")
    public R delete(Integer[] ids){

        Integer mylen= ids.length;
        for (int i = 0; i <mylen ; i++) {

            //读取数据,再删除
            //Device item = deviceService.findById(ids[i]).get();

            deviceService.delete(ids[i]);


        }

        return RUtil.success();

    }



}
